﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IdleTest.EFAndMVCDemo.IServices;
using IdleTest.EFAndMVCDemo.Models;

namespace IdleTest.EFAndMVCDemo.MvcUI.Controllers
{
    public class UserController : Controller
    {
        private IUserService userService;

        public UserController() : this(IocContainer.Instance<IUserService>())
        {
        }

        public UserController(IUserService userService)
        {
            this.userService = userService;
        }

        public ActionResult Register()
        {
            return View("Register");
        }

        [HttpPost]
        public ActionResult Register(UserModel model)
        {
            return View("Register");
        }

        public ActionResult Login(string returnUrl)
        {
            return View("Login");
        }

        [HttpPost]
        public ActionResult Login(string loginName, string password, string returnUrl)
        {
            var failedView = View("Login");
            if (string.IsNullOrEmpty(loginName) || string.IsNullOrEmpty(password))
            {
                return failedView;
            }

            if (userService.Login(new UserModel { LoginName = loginName, Password = password }))
            {
                if (string.IsNullOrEmpty(returnUrl))
                {
                    return RedirectToAction("Index", "Home");
                }

                return Redirect(returnUrl);
            }

            return failedView;
        }
    }
}
